// 表单字段配置系统
// 用于定义各个模块的表单字段，便于后续修改

const FormConfigs = {
  // 充值包管理表单配置
  rechargePackage: {
    fields: [
      {
        key: 'name',
        label: '充值包名称',
        type: 'input',
        required: true,
        placeholder: '请输入充值包名称',
        validation: {
          minLength: 2,
          maxLength: 20
        }
      },
      {
        key: 'amount',
        label: '充值金额',
        type: 'number',
        required: true,
        placeholder: '请输入充值金额',
        unit: '元',
        validation: {
          min: 1,
          max: 10000
        }
      },
      {
        key: 'bonus',
        label: '赠送金额',
        type: 'number',
        required: true,
        placeholder: '请输入赠送金额',
        unit: '元',
        validation: {
          min: 0,
          max: 5000
        }
      },
      {
        key: 'isRecommended',
        label: '是否推荐',
        type: 'switch',
        required: false,
        defaultValue: false
      },
      {
        key: 'label',
        label: '标签',
        type: 'select',
        required: false,
        options: [
          { value: '入门', label: '入门' },
          { value: '推荐', label: '推荐' },
          { value: '高频使用', label: '高频使用' },
          { value: 'VIP专享', label: 'VIP专享' }
        ],
        placeholder: '请选择标签'
      },
      {
        key: 'description',
        label: '描述',
        type: 'textarea',
        required: false,
        placeholder: '请输入充值包描述',
        maxLength: 200
      },
      {
        key: 'status',
        label: '状态',
        type: 'select',
        required: true,
        options: [
          { value: 1, label: '启用' },
          { value: 0, label: '禁用' }
        ],
        defaultValue: 1
      }
    ],
    computedFields: [
      {
        key: 'totalAmount',
        label: '总金额',
        formula: 'amount + bonus',
        readonly: true
      }
    ]
  },

  // 设备信息管理表单配置
  deviceInfo: {
    fields: [
      {
        key: 'name',
        label: '设备名称',
        type: 'input',
        required: true,
        placeholder: '请输入设备名称',
        validation: {
          minLength: 2,
          maxLength: 30
        }
      },
      {
        key: 'type',
        label: '设备类型',
        type: 'select',
        required: true,
        options: [
          { value: 'bath', label: '洗浴设备' },
          { value: 'dry', label: '烘干设备' },
          { value: 'blow', label: '吹水设备' },
          { value: 'access', label: '门禁设备' },
          { value: 'other', label: '其他设备' }
        ],
        placeholder: '请选择设备类型'
      },
      {
        key: 'category',
        label: '设备分类',
        type: 'input',
        required: true,
        placeholder: '请输入设备分类',
        validation: {
          minLength: 2,
          maxLength: 20
        }
      },
      {
        key: 'code',
        label: '设备编码',
        type: 'input',
        required: true,
        placeholder: '请输入设备编码',
        validation: {
          pattern: '^[A-Z0-9-_]+$',
          message: '设备编码只能包含大写字母、数字、横线和下划线'
        }
      },
      {
        key: 'price',
        label: '价格',
        type: 'number',
        required: true,
        placeholder: '请输入设备价格',
        unit: '元',
        validation: {
          min: 0,
          max: 1000
        }
      },
      {
        key: 'location',
        label: '设备位置',
        type: 'object',
        required: true,
        fields: [
          {
            key: 'room',
            label: '房间',
            type: 'input',
            required: true,
            placeholder: '请输入房间名称'
          },
          {
            key: 'position',
            label: '位置',
            type: 'input',
            required: true,
            placeholder: '请输入具体位置'
          }
        ]
      },
      {
        key: 'mqttConfig',
        label: 'MQTT配置',
        type: 'object',
        required: true,
        fields: [
          {
            key: 'appId',
            label: 'App ID',
            type: 'input',
            required: true,
            placeholder: '请输入App ID'
          },
          {
            key: 'deviceKey',
            label: '设备密钥',
            type: 'input',
            required: true,
            placeholder: '请输入设备密钥'
          },
          {
            key: 'deviceMAC',
            label: '设备MAC',
            type: 'input',
            required: true,
            placeholder: '请输入设备MAC地址'
          },
          {
            key: 'publishTopic',
            label: '发布主题',
            type: 'input',
            required: true,
            placeholder: '请输入发布主题'
          }
        ]
      },
      {
        key: 'status',
        label: '设备状态',
        type: 'select',
        required: true,
        options: [
          { value: 'AVAILABLE', label: '可用' },
          { value: 'IN_USE', label: '使用中' },
          { value: 'MAINTENANCE', label: '维护中' },
          { value: 'OFFLINE', label: '离线' }
        ],
        defaultValue: 'AVAILABLE'
      }
    ]
  },

  // 寄养房间管理表单配置
  fosterRoom: {
    fields: [
      {
        key: 'roomName',
        label: '房间名称',
        type: 'input',
        required: true,
        placeholder: '请输入房间名称',
        validation: {
          minLength: 2,
          maxLength: 30
        }
      },
      {
        key: 'roomType',
        label: '房间类型',
        type: 'select',
        required: true,
        options: [
          { value: 'single', label: '单人间' },
          { value: 'double', label: '双人间' },
          { value: 'suite', label: '套房' }
        ],
        placeholder: '请选择房间类型'
      },
      {
        key: 'size',
        label: '房间尺寸',
        type: 'input',
        required: true,
        placeholder: '如: 3m x 2m',
        validation: {
          pattern: '^\\d+(\\.\\d+)?m\\s*x\\s*\\d+(\\.\\d+)?m$',
          message: '请输入正确的尺寸格式，如: 3m x 2m'
        }
      },
      {
        key: 'capacity',
        label: '容纳数量',
        type: 'number',
        required: true,
        placeholder: '请输入容纳宠物数量',
        unit: '只',
        validation: {
          min: 1,
          max: 10
        }
      },
      {
        key: 'price',
        label: '价格',
        type: 'number',
        required: true,
        placeholder: '请输入房间价格',
        unit: '元',
        validation: {
          min: 0,
          max: 1000
        }
      },
      {
        key: 'unit',
        label: '价格单位',
        type: 'select',
        required: true,
        options: [
          { value: '次', label: '次' },
          { value: '天', label: '天' },
          { value: '小时', label: '小时' }
        ],
        defaultValue: '天'
      },
      {
        key: 'description',
        label: '房间描述',
        type: 'textarea',
        required: false,
        placeholder: '请输入房间描述',
        maxLength: 500
      },
      {
        key: 'amenities',
        label: '房间设施',
        type: 'array',
        required: false,
        itemType: 'input',
        placeholder: '请输入设施名称',
        addButtonText: '添加设施'
      },
      {
        key: 'careInstructions',
        label: '护理说明',
        type: 'array',
        required: false,
        itemType: 'textarea',
        placeholder: '请输入护理说明',
        addButtonText: '添加说明'
      },
      {
        key: 'status',
        label: '房间状态',
        type: 'select',
        required: true,
        options: [
          { value: 'available', label: '可用' },
          { value: 'occupied', label: '已占用' },
          { value: 'maintenance', label: '维护中' },
          { value: 'disabled', label: '停用' }
        ],
        defaultValue: 'available'
      }
    ]
  },

  // 新闻管理表单配置
  news: {
    fields: [
      {
        key: 'NEWS_TITLE',
        label: '新闻标题',
        type: 'input',
        required: true,
        placeholder: '请输入新闻标题',
        validation: {
          minLength: 2,
          maxLength: 100
        }
      },
      {
        key: 'NEWS_DESC',
        label: '新闻摘要',
        type: 'textarea',
        required: false,
        placeholder: '请输入新闻摘要',
        maxLength: 300
      },
      {
        key: 'NEWS_CONTENT',
        label: '新闻内容',
        type: 'textarea',
        required: true,
        placeholder: '请输入新闻内容',
        maxLength: 5000
      },
      {
        key: 'NEWS_CATE_NAME',
        label: '新闻分类',
        type: 'select',
        required: true,
        options: [
          { value: '公告', label: '公告' },
          { value: '活动', label: '活动' },
          { value: '服务', label: '服务' },
          { value: '其他', label: '其他' }
        ],
        placeholder: '请选择新闻分类'
      },
      {
        key: 'NEWS_ORDER',
        label: '排序序号',
        type: 'number',
        required: false,
        placeholder: '请输入排序序号',
        validation: {
          min: 0,
          max: 9999
        },
        defaultValue: 0
      },
      {
        key: 'NEWS_HOME',
        label: '是否置顶',
        type: 'switch',
        required: false,
        defaultValue: false
      },
      {
        key: 'NEWS_STATUS',
        label: '发布状态',
        type: 'select',
        required: true,
        options: [
          { value: 1, label: '已发布' },
          { value: 0, label: '草稿' }
        ],
        defaultValue: 1
      }
    ]
  }
};

// 表单验证规则
const ValidationRules = {
  required: (value) => {
    if (typeof value === 'string') {
      return value.trim().length > 0;
    }
    return value !== null && value !== undefined;
  },
  
  minLength: (value, min) => {
    return typeof value === 'string' && value.length >= min;
  },
  
  maxLength: (value, max) => {
    return typeof value === 'string' && value.length <= max;
  },
  
  min: (value, min) => {
    return typeof value === 'number' && value >= min;
  },
  
  max: (value, max) => {
    return typeof value === 'number' && value <= max;
  },
  
  pattern: (value, pattern) => {
    const regex = new RegExp(pattern);
    return typeof value === 'string' && regex.test(value);
  }
};

// 表单工具函数
const FormUtils = {
  // 获取表单配置
  getFormConfig: (formType) => {
    return FormConfigs[formType] || null;
  },
  
  // 验证表单字段
  validateField: (field, value) => {
    const errors = [];
    
    // 必填验证
    if (field.required && !ValidationRules.required(value)) {
      errors.push(`${field.label}不能为空`);
    }
    
    // 其他验证规则
    if (field.validation && value !== null && value !== undefined) {
      Object.keys(field.validation).forEach(rule => {
        if (ValidationRules[rule]) {
          const isValid = ValidationRules[rule](value, field.validation[rule]);
          if (!isValid) {
            const message = field.validation.message || `${field.label}格式不正确`;
            errors.push(message);
          }
        }
      });
    }
    
    return errors;
  },
  
  // 验证整个表单
  validateForm: (formType, formData) => {
    const config = FormConfigs[formType];
    if (!config) return { isValid: false, errors: ['未知的表单类型'] };
    
    const errors = {};
    let isValid = true;
    
    config.fields.forEach(field => {
      const fieldErrors = FormUtils.validateField(field, formData[field.key]);
      if (fieldErrors.length > 0) {
        errors[field.key] = fieldErrors;
        isValid = false;
      }
    });
    
    return { isValid, errors };
  },
  
  // 计算计算字段
  calculateFields: (formType, formData) => {
    const config = FormConfigs[formType];
    if (!config || !config.computedFields) return formData;
    
    const result = { ...formData };
    
    config.computedFields.forEach(field => {
      if (field.formula) {
        // 简单的公式计算，实际项目中可以使用更复杂的表达式解析器
        try {
          const expression = field.formula.replace(/amount/g, formData.amount || 0).replace(/bonus/g, formData.bonus || 0);
          result[field.key] = eval(expression);
        } catch (error) {
          console.error('计算字段失败:', error);
        }
      }
    });
    
    return result;
  },
  
  // 获取字段默认值
  getDefaultValue: (field) => {
    if (field.defaultValue !== undefined) {
      return field.defaultValue;
    }
    
    switch (field.type) {
      case 'input':
      case 'textarea':
        return '';
      case 'number':
        return 0;
      case 'select':
        return field.options && field.options.length > 0 ? field.options[0].value : '';
      case 'switch':
        return false;
      case 'array':
        return [];
      case 'object':
        return {};
      default:
        return null;
    }
  },
  
  // 初始化表单数据
  initFormData: (formType) => {
    const config = FormConfigs[formType];
    if (!config) return {};
    
    const formData = {};
    config.fields.forEach(field => {
      formData[field.key] = FormUtils.getDefaultValue(field);
    });
    
    return formData;
  }
};

module.exports = {
  FormConfigs,
  ValidationRules,
  FormUtils
};
